<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreReportRequest;
use App\Models\Post;
use App\Models\Reply;
use App\Services\ReportService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ReportController extends Controller
{
    public function __construct(
        private ReportService $reportService
    ) {}

    /**
     * 显示举报表单
     */
    public function create(Request $request): Response
    {
        $type = $request->input('type'); // post, reply
        $id = $request->input('id');

        return Inertia::render('Reports/Create', [
            'type' => $type,
            'id' => $id,
        ]);
    }

    /**
     * 提交举报
     */
    public function store(StoreReportRequest $request)
    {
        $type = $request->input('type'); // post, reply
        $id = $request->input('id');

        if (! $type || ! $id) {
            return redirect()->back()->withErrors(['error' => '缺少必要参数']);
        }

        // 根据类型获取被举报的对象
        try {
            $reportable = match ($type) {
                'post' => Post::findOrFail($id),
                'reply' => Reply::findOrFail($id),
                default => throw new \InvalidArgumentException('不支持的举报类型: '.$type),
            };
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->back()->withErrors(['error' => '要举报的内容不存在']);
        } catch (\InvalidArgumentException $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }

        try {
            $report = $this->reportService->createReport(
                $request->user(),
                $reportable,
                $request->validated()
            );

            return redirect()->back()->with('success', '举报已提交，我们会尽快处理');
        } catch (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
